package com.scuola.scuoladocente;

import java.util.ArrayList;
import java.util.LinkedHashMap;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class CreaAvvisiActivity extends Activity {

	private String destId = null;
	private String msg = null;
	private JSONArray parsedList = null;
	private JSONParser parser = new JSONParser();
	private  AutoCompleteTextView avvisiAutocompleteDestinatari;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_crea_avvisi);
        avvisiAutocompleteDestinatari  = (AutoCompleteTextView)findViewById(R.id.avvisi_autocomplete_destinatari);
        
        try {
        	AsyncTask<Void, Void, String> getAlumniByClassIdResponse = new getAlumniByClassId().execute();
			parsedList = (JSONArray) parser.parse(getAlumniByClassIdResponse.get());
			
			String items[] = new String[parsedList.size()+1];
			items[0] = "Tutti gli Alunni";
			for(int i = 0; i < parsedList.size(); i++){
				JSONObject obj = (JSONObject) parser.parse(parsedList.get(i).toString());
				String tmp = obj.get("cognome").toString()+" "+obj.get("nome").toString();
				items[i+1] = tmp;
			}
			
			ArrayAdapter<String> aAdapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_dropdown_item_1line, items);
			avvisiAutocompleteDestinatari.setAdapter(aAdapter);
			
			JSONObject obj = new JSONObject();
			obj.put("id", "0");
			obj.put("cognome", "Tutti");
			obj.put("nome", "gli Alunni");
			parsedList.add(obj);
			
			final Button inviaAvviso = (Button)findViewById(R.id.avvisi_invia);
			inviaAvviso.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	try{
            		int exist = 0;
            		for(int i = 0; i < parsedList.size(); i++){
            			JSONObject obj = (JSONObject) parser.parse(parsedList.get(i).toString());
        				String tmp = obj.get("cognome").toString()+" "+obj.get("nome").toString();
        				if(tmp.equals(avvisiAutocompleteDestinatari.getText().toString())){
        					destId = obj.get("id").toString();
        					EditText messaggio = (EditText)findViewById(R.id.avvisi_messaggio);
        					msg = messaggio.getText().toString();
        					AsyncTask<Void, Void, String> setAvvisoResponse = new setAvviso().execute();
        					String res = setAvvisoResponse.get();
        					if(res.equals("OK")){
            					Toast msg = Toast.makeText(getApplicationContext(), "Avviso inviato corretamente", Toast.LENGTH_SHORT);
            					msg.show();
        					}else{
            					Toast msg = Toast.makeText(getApplicationContext(), "Errore invio! Riprova!", Toast.LENGTH_SHORT);
            					msg.show();
        					}
        					exist = 1;
        				}
            		}
    				if(exist == 0){
    					Toast msg = Toast.makeText(getApplicationContext(), "Controlla il Destinatario", Toast.LENGTH_SHORT);
    					msg.show();
    				}else{
    					finish();
    				}
        		}catch(Exception ex){
            		ex.printStackTrace();
            	}
        	}
		}); 
			if(getIntent().getStringExtra("id_mittente") != null){
				avvisiAutocompleteDestinatari.setFocusable(false);
				avvisiAutocompleteDestinatari.setFocusableInTouchMode(false);
				avvisiAutocompleteDestinatari.setText(getIntent().getStringExtra("cognome").toString()+" "+getIntent().getStringExtra("nome").toString());
			}
			
        }catch(Exception e){
        	e.printStackTrace();
        }
    }
    
    private class getAlumniByClassId extends AsyncTask<Void, Void, String>{
		@Override
		protected String doInBackground(Void... arg0) {
			try{	
				LinkedHashMap<String, String> hm = new LinkedHashMap<String, String>();
				hm.put("classId", getIntent().getStringExtra("idclasse"));
				String strResponse = operations.wsCall("getAlumniByClassId", hm).toString();
				return strResponse;
				
			} catch (Exception e) {
				System.err.println("getAlumniByClassId errore (Exception)");
				e.printStackTrace();
				return null;
			}
		
		}
    }
    
    private class setAvviso extends AsyncTask<Void, Void, String>{
		@Override
		protected String doInBackground(Void... arg0) {
			try{	
				LinkedHashMap<String, String> hm = new LinkedHashMap<String, String>();
				hm.put("classId", getIntent().getStringExtra("idclasse"));
				hm.put("mittenteId", getIntent().getStringExtra("idutente"));
				hm.put("destId", destId);
				hm.put("messaggio", msg);
				String strResponse = operations.wsCall("setAvviso", hm).toString();
				return strResponse;
				
			} catch (Exception e) {
				System.err.println("setAvviso errore (Exception)");
				e.printStackTrace();
				return null;
			}
		
		}
    }
}
